//
//  SEGServiceMessageViewController.m
//  ExcellentHome
//
//  Created by 揭婧雯 on 2017/11/16.
//  Copyright © 2017年 陈区. All rights reserved.
//

#import "SEGServiceMessageViewController.h"

#import "SEGSystemMessageViewController.h"
#import "SEGPropertyTableViewCell.h"
#import "SEGSubMessageModel.h"

#import "SEGServiceMessageViewModel.h"

@interface SEGServiceMessageViewController () <UITableViewDelegate, UITableViewDataSource>

/// 表格
@property (nonatomic, strong) UITableView* tableView;
/// 底部菜单栏
@property (nonatomic, strong) UIView *menuView;
 
/// viewModel
@property (nonatomic, strong) SEGServiceMessageViewModel *viewModel;

@end

@implementation SEGServiceMessageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = kColor_W;
    self.title = self.baseInfoModel.serviceNumberName;

    // 请求数据
    [self seg_loadData];
    WeakSelf;
    [self.tableView addWindmillWithHeaderRefreshBlock:^{
        [weakSelf seg_getMsgV3];
    }];
    [self.tableView beginHeaderRefreshing];
}

#pragma mark - Load Data
// 底部菜单逻辑
- (void)seg_loadData {
    @weakify(self);
    RACTuple *tuple = RACTuplePack(self.baseInfoModel.serviceNbr, self.baseInfoModel.serviceNumberId);
    [[self.viewModel.menuListCommand execute:tuple] subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        [self seg_showMenuView];
    } error:^(NSError * _Nullable error) {
        [SEGAlertView showTmepMessageWithMessage:error.localizedFailureReason];
    }];
}
// 获取消息数据
- (void)seg_getMsgV3 {
    @weakify(self);
    [[self.viewModel.msgV3Command execute:self.groupId] subscribeNext:^(NSNumber *dataCount) {
        @strongify(self);
        [self.tableView stopAnimatingWindmill];
        if (dataCount.integerValue > 0) {
            [[SEGUhomeMediator sharedInstance] seg_hideCustomProgressImage:@{@"view":self.tableView}];
            [self.tableView reloadData];
        } else {
            [[SEGUhomeMediator sharedInstance] seg_showCustomProgressImage:@{@"view":self.tableView}];
        }
    }];
}

#pragma mark - UI
- (void)seg_hiddenMenu {
    [self.view.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.tag >= 100) {
            obj.hidden = YES;
        }
    }];
}
- (void)seg_showMenuView {
    if (self.viewModel.messManager.servicenbrMenuListModel.count == 0) return;
    
    self.tableView.frame = CGRectMake(0, 0, LYScreenWidth(), LYScreenHeight() - kNavigationBarAndStatusBarHeight - 44 - LYSafeAreaBottom());
    //数字社区逻辑
    NSMutableArray *tempArray = [NSMutableArray array];
    [self.viewModel.messManager.servicenbrMenuListModel enumerateObjectsUsingBlock:^(SEGMenuListModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (![obj.resCode isEqualToString:@"RES_PROPERTY_NOTICE"]) {
            [tempArray addObject:obj];
        } else {//物业资讯显示在导航栏上
            self.viewModel.digitalCommunityModel = obj;
//            NSString *aTitle = @"数字社区";
             NSString *aTitle = obj.serviceName;
            
            // !!!:  Wendy，2018.1.10, 解决标题和右边文字重叠问题
            CGFloat leftPadding;
            if (kScreenWidth > 375.0) {//默认情况下，在320、375宽度的屏幕上，第一个按钮距离屏幕左边界的宽度是16，在414第一个按钮距离屏幕左边界的宽度是20。
                leftPadding = 20;
            } else {
                leftPadding = 16;
            }
            CGFloat itemPadding;
//            if (@available(iOS 11.0, *)) {//在iOS11之前，titleview和barbutton之间的间距是6p，在iOS11上titleview和barbutton之间无间距
//                itemPadding = 0;
//            }else {
                itemPadding = 6;
//            }

            // TODO: 标题需要进行改造-组件化
/***********/
//            CGFloat leftPad = (leftPadding + itemPadding + self.leftBarbuttonWidth);
//
//            CGSize size = STRING_SIZE_FONT(1000, aTitle, 14);
//            CGFloat rightPad = (leftPadding + itemPadding + size.width);
//            CGFloat width = LYScreenWidth() - leftPad - rightPad;
//
//            m_titleView.frame = CGRectMake(0, 0, width, 40);//在iOS11以前可能失效，宽度取决于左右两边的按钮
//            m_lbTitle.frame = CGRectMake(0, 0, width, 40);//两层解决iOS10以前宽度失效问题
//            self.navigationItem.titleView = m_titleView;
/***********/
            
            [self showCustomNavigationRightButtonWithTitle:aTitle image:nil hightlightImage:nil color:kColor_1];
        }
    }];
    self.viewModel.menuListModelArray = tempArray;
    
    
    CGFloat width = LYScreenWidth() / self.viewModel.menuListModelArray.count;
    [self.viewModel.menuListModelArray enumerateObjectsUsingBlock:^(SEGMenuListModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIButton *button = [[UIButton alloc] init];
        [button setTitle:obj.serviceName forState:UIControlStateNormal];
        [button setTitleColor:kColor_1 forState:UIControlStateNormal];
        button.titleLabel.font = kFont_16;
        button.tag = idx;
//        button.backgroundColor = kColor_T;
        [button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
        [self.menuView addSubview:button];
        [button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.menuView);
            make.centerY.equalTo(self.menuView);
            make.left.equalTo(self.menuView).offset(width * idx);
            make.width.mas_equalTo(width);
        }];
        if (idx != 0) {
            //竖分隔线
            UIView *line = [[UIView alloc] init];
            line.backgroundColor = kColor_L4;
            [self.menuView addSubview:line];
            [line mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(button);
                make.top.equalTo(self.menuView).offset(10);
                make.bottom.equalTo(self.menuView).offset(-10);
                make.width.mas_equalTo(0.5);
            }];
        }
        if (obj.childList && obj.childList.count > 0) {
            CGFloat imageWidth = 120;
            CGFloat imageHeight = obj.childList.count * 44.0 + 7;//箭头高度为7
            UIImageView *bgView = [[UIImageView alloc] init];
//            bgView.backgroundColor = kColor_T;
            UIEdgeInsets insets = UIEdgeInsetsMake(10, 10, 10, 10);
            bgView.image = [[UIImage imageWithContentsOfFile:SEGPicName(@"bg_xiaoxi_tab")] resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch];
            bgView.tag = idx + 100;
            bgView.hidden = YES;
            bgView.userInteractionEnabled = YES;
            [self.view addSubview:bgView];
            [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.bottom.equalTo(button.mas_top).offset(-5);
                make.height.mas_equalTo(imageHeight);
                make.width.mas_equalTo(imageWidth);
                if (idx == 0) {//最左边的菜单
                    make.left.equalTo(self.menuView).offset(10);
                } else if (idx == self.viewModel.menuListModelArray.count - 1) {//最右边的
                    make.right.equalTo(self.menuView).offset(-10);
                } else {
                    make.centerX.equalTo(button);
                }
            }];
            [obj.childList enumerateObjectsUsingBlock:^(SEGMenuListModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                
                UIButton *itemButton = [[UIButton alloc] init];
                [itemButton setTitle:obj.serviceName forState:UIControlStateNormal];
                [itemButton setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
                itemButton.titleLabel.font = kFont_15;
                itemButton.tag = idx;
                [itemButton addTarget:self action:@selector(itemButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
                [bgView addSubview:itemButton];
                [itemButton mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.top.equalTo(bgView).offset(44.0 * idx);
                    make.height.mas_equalTo(44.0);
                    make.left.equalTo(bgView);
                    make.right.equalTo(bgView);
                }];
                
                if (idx != 0) {
                    UIView *line2 = [[UIView alloc] init];
                    line2.backgroundColor = kColor_L4;
                    [bgView addSubview:line2];
                    [line2 mas_makeConstraints:^(MASConstraintMaker *make) {
                        make.left.equalTo(bgView).mas_offset(10);
                        make.right.equalTo(bgView).mas_offset(-10);
                        make.top.equalTo(itemButton);
                        make.height.mas_equalTo(0.5);
                    }];
                }
            }];
        }
    }];
}

#pragma mark - Event
- (void)onNavigationRightButtonClicked:(UIButton*)sender {
    [self seg_hiddenMenu];
    [self seg_jumpToVCWithModel:self.viewModel.digitalCommunityModel];
}
- (void)buttonPressed:(UIButton *)button {
    NSInteger index = button.tag;
    SEGMenuListModel *model = self.viewModel.menuListModelArray[index];
    if (model.childList.count == 0) {
        [self seg_hiddenMenu];
        [self seg_jumpToVCWithModel:model];
    }else {
        [self.view.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (obj.tag >= 100) {
                if (obj.tag == button.tag + 100) {
                    obj.hidden = !obj.hidden;
                }else {
                    obj.hidden = YES;
                }
            }
        }];
    }
}
- (void)itemButtonPressed:(UIButton *)button {
    __block NSInteger currentMenuIndex = 0;
    [self.view.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.tag >= 100) {
            if (obj.hidden == NO) {
                currentMenuIndex = obj.tag - 100;
                obj.hidden = YES;
                *stop = YES;
            }
        }
    }];
    SEGMenuListModel *model = self.viewModel.menuListModelArray[currentMenuIndex];
    SEGMenuListModel *childModel = model.childList[button.tag];
    [self seg_jumpToVCWithModel:childModel];
}
- (void)seg_jumpToVCWithModel:(SEGMenuListModel *)data {
//    NSDictionary *userInfo = @{
//                               @"type":ValueToString(data.type),
//                               @"isBrowser":ValueToString(data.isBrowser),
//                               @"userType":ValueToString(data.userType),
//                               @"tempInstId":ValueToString(data.templateInstId),
//                               @"serviceName":ValueToString(data.serviceName),
//                               @"action":ValueToString(data.action),
//                               @"instCode":ValueToString(data.instCode),
//                               @"nodeTempInstId":ValueToString(data.nodeTempInstId)
//                               };
    [[SEGUhomeMediator sharedInstance] seg_pushToViewControllerWithAction:[data yy_modelToJSONObject]];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.viewModel.dataArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SEGPropertyTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"cellId"];
    if (cell == nil) {
        cell = [[SEGPropertyTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cellId"];
    }
    MessageModel *model = self.viewModel.dataArray[indexPath.section];
    [cell cellWithModel:model];
    return cell;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    MessageModel* model = self.viewModel.dataArray[section];
    static NSString * headIdenty = @"headFootView";
    UITableViewHeaderFooterView * head = [tableView dequeueReusableHeaderFooterViewWithIdentifier:headIdenty];
    if (!head) {
        head = [[UITableViewHeaderFooterView alloc]initWithReuseIdentifier:headIdenty];
        UIView *timeView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, LYScreenWidth(), 44)];
        timeView.backgroundColor = kColor_bg;
        
        UILabel *dateLabel = [[UILabel alloc] init];
        dateLabel.textColor = kColor_3;
        dateLabel.font = [UIFont systemFontOfSize:13];
        dateLabel.tag = 100;
        
        [timeView addSubview:dateLabel];
        [dateLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(timeView).mas_offset(15);
            make.center.equalTo(timeView);
        }];
        [head addSubview:timeView];
    }
    
    UILabel *label = (UILabel *)[head viewWithTag:100];
    label.text = [SEGUtils getTimeStringInMessageDetailVCWithString:model.createTime];
    return head;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 44;
}
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 67.0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewAutomaticDimension;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self seg_hiddenMenu];
    MessageModel *msgModel = self.viewModel.dataArray[indexPath.section];
    // 根据type跳转页面
    [[SEGUhomeMediator sharedInstance] seg_pushToViewControllerWithMessageType:@{@"model":msgModel, @"nav":self.navigationController}];
}

#pragma mark - Getter
- (SEGServiceMessageViewModel *)viewModel {
    if (!_viewModel) _viewModel = [SEGServiceMessageViewModel new];
    return _viewModel;
}
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, LYScreenWidth(), LYScreenHeight() - kNavigationBarAndStatusBarHeight) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableFooterView = [UIView new];
        _tableView.sectionFooterHeight = 0;
        _tableView.backgroundColor = kColor_bg;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:[SEGPropertyTableViewCell class] forCellReuseIdentifier:@"cellId"];
        [self.view addSubview:_tableView];
    }
    return _tableView;
}
- (UIView *)menuView {
    if (!_menuView) {
        _menuView = [[UIView alloc] init];
        _menuView.backgroundColor = kColor_W;
        [self.view addSubview:_menuView];
        [_menuView mas_makeConstraints:^(MASConstraintMaker* make) {
            make.left.equalTo(self.view.mas_left);
            make.right.equalTo(self.view.mas_right);
            make.bottom.equalTo(self.view.mas_bottom).offset(-LYSafeAreaBottom());
            make.height.mas_equalTo(44.0);
        }];
        UIView *line = [[UIView alloc] init];
        line.backgroundColor = kColor_L2;
        [_menuView addSubview:line];
        [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self->_menuView);
            make.right.equalTo(self->_menuView);
            make.top.equalTo(self->_menuView);
            make.height.mas_equalTo(0.5);
        }];
    }
    return _menuView;
}

@end
